<?php

namespace app\common\entity;

use think\Db;
use think\Model;

class Mywallet extends Model
{
    /**
     * @var string 对应的数据表名
     */
    protected $table = 'my_wallet';

    protected $autoWriteTimestamp = true;

    /**
     * [获取会员余额]
     * @param
     * @return
     */
    public function balance($uid,$field='bless'){
        return self::where('user_id',$uid)->value($field);
    }
    /**
     * [获取审核状态]
     * @param
     * @return
     */
    public static function getUidInfo($uid){
        return self::where('user_id',$uid)->find();
    }
    /**
     * [余额是否够]
     * @return
     */
    public function checkbalance($uid,$number =0,$field='bless'){
        $balance = $this->balance($uid,$field);
        if($balance >= $number) return true;// 够
        return false;
    }


    #满多少给矿机
    public function getMachine($uid)
    {
        $machine = new MachineList();
        $hasMachine = new HasMachine();
        $totalNum = self::where('user_id', $uid)->value('total_num');
        for ($a = 1; $a <= 4; $a++) {
            $res = $this->insMachine($hasMachine, $machine, $uid, $a, $totalNum);
        }
        return true;


    }

    public function makeAct($uid)
    {

    }

    public function insMachine($hasMachine, $machine, $uid, $types, $totalNum)
    {
        $level1 = UserPackage::where('level', $types)->find();
        $level100 = floor($totalNum / $level1['money']);
        if ($level100 <= 0) {
            return true;
        }
        $has100Num = MachineList::where('user_id', $uid)->where('types', $types)->count();
        if ($has100Num >= $level100) {
            return true;
        }
        $insNum = $level100 - $has100Num;
        for ($i = 0; $i < $insNum; $i++) {
            $machine->addList($uid, $types, $types);
            $hasMachine->updMachineNum($uid, $types);
        }
        return true;
    }

    #获取下级
    public function getChildsInfo($uid)
    {
        $childs = [];

        $my = User::where('id', $uid)->field('id,pid')->find();
        $one = User::where('id', $my['pid'])->field('id,pid')->find();
        $one['levels'] = 1;
        $childs[] = $one;
        $two = User::where('id', $one['pid'])->field('id,pid')->find();
        if (!$two) {
            return $childs;
        }
        $two['levels'] = 2;
        $childs[] = $two;


        return $childs;
    }

    public function getParentsNb($uid, &$parent = array(), &$level = 0)
    {
        // static $parent = [];
        // static $level = 0;
        $userInfo = User::where('id', $uid)->field('id,pid')->find();

        $pid = $userInfo['pid'];

        if ($pid == '0') {
            $userInfo['levels'] = $level;
            $parent[] = $userInfo;
            return $parent;
        }
        if ($level == '0') {
            $level++;
        } else {

            $userInfo['levels'] = $level;
            $parent[] = $userInfo;
            $level++;
        }
        $this->getParentsNb($pid, $parent, $level);
        return $parent;

    }

    #获取上一级
    public function getParents($uid, $num = 0, &$parent = array(), &$level = 0)
    {
        // static $parent = [];
        // static $level = 0;
        $userInfo = User::where('id', $uid)->find();

        $pid = $userInfo['pid'];
        $level++;
        if ($num > 0) {

            if ($level > $num) {
                return $parent;
            }
        }
        if ($pid == '0') {
            return $parent;
        }
        $parent["$level"] = $pid;
        $this->getParents($pid, $num, $parent, $level);
        return $parent;

    }
//     #静态收益
//     public function share($uid,$num,&$l= 0)
//     {

//         $parents = $this->getParents($uid);
//         $userModel = new User();
//         $mywalletLog = new MywalletLog();
//         $mobile = $userModel->where('id',$uid)->value('mobile');
//         foreach ($parents as $k=>$v ){
//             $level = $userModel->getUserLevel($v);
//             $zhitui = $userModel->getZhitui($v);
//             $getShareRatio = ShareConfig::where('level',$level)->where('child',$k)->where('count','<=',$zhitui)->value('ratio');
// //            dump($getShareRatio);die;
//             if (!$getShareRatio){
//                 continue;
//             }
//             $shareNum = $num * $getShareRatio;
//             $l++;
//             $insLog = $mywalletLog->addLog($v,$shareNum,'number','团队收益',1,1);
//             $updwallet = Mywallet::where('user_id',$v)->setInc('number',$shareNum);
//             $updwallet_total = Mywallet::where('user_id',$v)->setInc('team_hash',$shareNum);

//             if ($updwallet){
//                 $this->share($v,$shareNum,$l);
//             }
//         }
//         return $l;
//     }

    #静态收益(矿机产币)
    public function share($uid, $num, $l = 0)
    {

        $parents = $this->getParents($uid, 3);
        $userModel = new User();
        $mywalletLog = new MywalletLog();
        $mobile = $userModel->where('id', $uid)->value('mobile');
        foreach ($parents as $k => $v) {
            $level = $userModel->getUserLevel($v);
            if ($level == '0') {
                continue;
            }
            $getShareRatio = UserLevelSend::where('level', $level)->find();

            if ($getShareRatio['share' . $k] == '0') {
                continue;
            }
            $shareNum = $num * ($getShareRatio['share' . $k] / 100);
            $l++;
            $insLog = $mywalletLog->addLog($v, $shareNum, 'sell_number', '团队奖' . $getShareRatio['share' . $k] . '%,第' . $k . '级,会员' . $mobile, 3, 1);
            $updwallet = Mywallet::where('user_id', $v)->setInc('sell_number', $shareNum);
            $updwallet1 = Mywallet::where('user_id', $v)->setInc('bonus_total', $shareNum);

        }
        return $l;
    }


    #静态收益(买币奖励)
    public function buyshare($uid, $num, $l = 0)
    {

        $parents = $this->getParents($uid, 4);
        $userModel = new User();
        $mywalletLog = new MywalletLog();
        $mobile = $userModel->where('id', $uid)->value('mobile');
        foreach ($parents as $k => $v) {
            $level = $userModel->getUserLevel($v);
            if ($level == '0') {
                continue;
            }
            $getShareRatio = UserLevelSend::where('level', $level)->find();

            if ($getShareRatio['buy_share' . $k] == '0') {
                continue;
            }
            $shareNum = $num * ($getShareRatio['buy_share' . $k] / 100);
            $l++;
            $insLog = $mywalletLog->addLog($v, $shareNum, 'number', '团队奖' . $getShareRatio['buy_share' . $k] . '%,第' . $k . '级,会员' . $mobile, 1, 1);
            $updwallet = Mywallet::where('user_id', $v)->setInc('number', $shareNum);
            $updwallet1 = Mywallet::where('user_id', $v)->setInc('bonus_total', $shareNum);

        }
        return $l;
    }

    public function utshare($uid, $num, $l = 0)
    {

        $userModel = new User();
        $maxLevelRatio = UserLevelSend::order('ut_dai desc')->value('ut_dai');

        $parents = $this->getParents($uid, $maxLevelRatio);
        $mywalletLog = new MywalletLog();
        $mobile = $userModel->where('id', $uid)->value('nick_name');
        foreach ($parents as $k => $v) {
            $level = $userModel->getUserLevel($v);

            $getShareRatio = UserLevelSend::where('level', $level)->find();

            if ($getShareRatio['ut_dai'] < $k) {
                continue;
            }
            $shareNum = $num * ($getShareRatio['ut_ratio'] / 100);
            $l++;
            $insLog = $mywalletLog->addLog($v, $shareNum, 'ht_num', '团队奖' . $getShareRatio['ut_ratio'] . '%,第' . $k . '级,会员' . $mobile, 7, 1);
            $updwallet = Mywallet::where('user_id', $v)->setInc('ht_num', $shareNum);
            $updwallet1 = Mywallet::where('user_id', $v)->setInc('bonus_total', $shareNum);

        }
        return $l;
    }

    #动态
    public function shareDon($uid, $num)
    {
        die;
        $parents = $this->getParents($uid);
        $userModel = new User();
        $mywalletLog = new MywalletLog();
        $mobile = $userModel->where('id', $uid)->value('mobile');
        foreach ($parents as $k => $v) {
            $level = $userModel->getUserLevel($v);
            $zhitui = $userModel->getZhitui($v);
            $getShareRatio = ShareConfig::where('level', $level)->where('child', $k)->where('count', '<=', $zhitui)->value('ratio');
//            dump($getShareRatio);die;
            if (!$getShareRatio) {
                continue;
            }
            $shareNum = $num * $getShareRatio;
            $insLog = $mywalletLog->addLog($v, $shareNum, 'number', '团队动态收益', 1, 1);
            $updwallet = Mywallet::where('user_id', $v)->setInc('number', $shareNum);
            $updwallet1 = Mywallet::where('user_id', $v)->setInc('bonus_total', $shareNum);
            $updwallet_total = Mywallet::where('user_id', $v)->setInc('team_hash', $shareNum);

            if ($updwallet) {
                $this->shareDon($v, $shareNum);
            }
        }
        return true;
    }


    #购买商品上级增加团队业绩
    public function upParentsHash($uid, $num)
    {
        $parents = $this->getParents($uid);
        foreach ($parents as $k => $v) {
            $updWallet = self::where('user_id', $v)->setInc('total_num', $num);
            $this->userLevelUpd($v);
        }

        return true;
    }

    #每小时更新可领取量
    public function updMachineGet($uid)
    {
        // file_put_contents(dirname(__FILE__).'/dsads'.date('ymd_His'),6666 );
        $list = Db('machine_list')->where('status', 1)->where('update_time', '<=', time() - 100)->where('user_id', $uid)->limit(50)->select();

        $a = count($list);
        foreach ($list as $v) {
            $time = time() - $v['get_time'];
            if ($time >= (3600 * 24)) {//3600 * 24
                $is_24 = 2;
            } else {
                $is_24 = 1;
            }
            $this->machineMake($v['id'], $v['get_num'], $v['level'], $time, $is_24);
        }
        return true;

    }

    #每小时更新每日获得
    public function machineMake($machine_id, $get_num, $level, $time, $is_24)
    {
        $UserPackage = Db('user_package')->where('level', $level)->find();
        $total_num = $UserPackage['total_num'];
        $day_get = $UserPackage['num'];
        // $machineInfo = Db('machine_list')->where('id', $machine_id)->find();
        if ($get_num >= $total_num) {
            //过期
            $updStatus = Db('machine_list')->where('id', $machine_id)->update(['status' => 2]);
            return false;
        }
        if ($time >= 3600 * 24) {//60*5  3600 * 24
            $updtoday = Db('machine_list')->where('id', $machine_id)->update(['today_get' => 1]);
        }

        // $day_get = Db('user_package')->where('level', $level)->value('num');
        $miao_get = $day_get / 24 / 3600;
        $upd_can_get = $miao_get * $time;
        if ($is_24 == 1) {
            $upd = Db('machine_list')->where('id', $machine_id)->update(['can_get_num' => $upd_can_get, 'is_24' => $is_24, 'update_time' => time()]);
        } else {
            $upd = Db('machine_list')->where('id', $machine_id)->update(['can_get_num' => $day_get, 'is_24' => $is_24, 'update_time' => time()]);
        }
        if ($upd) {
            return true;
        }
        return false;
    }


    #团队奖励
    public function teamShare($uid, $num, $goods_id, $types = 1)
    {
        $userModel = new User();
        $mywalletModel = new self();
        $mywalletLogModel = new MywalletLog();
        $userLevelSend = new UserLevelSend();
        $myUserInfo = $userModel->where('id', $uid)->find();
        if ($myUserInfo['pid'] == 0) {
            return true;
        }

        $parentArr = $this->getParents($uid);

        //同级奖励
//        $sameRatio = 0.01;

        //分销奖励
        if ($types == 1) {

            $goodsInfo = Goods::where('id', $goods_id)->find();

        } else {
            $goodsInfo = UserPackage::where('id', $goods_id)->find();
        }
        $f = [
            1 => $goodsInfo['share1'] / 100,
            2 => $goodsInfo['share2'] / 100,
            3 => $goodsInfo['share3'] / 100,
        ];
//        $t = [
//            1 => ($userLevelSend->where('level', 1)->value('team_ratio')) / 100,
//            2 => ($userLevelSend->where('level', 2)->value('team_ratio')) / 100,
//            3 => ($userLevelSend->where('level', 3)->value('team_ratio')) / 100,
//            4 => ($userLevelSend->where('level', 4)->value('team_ratio')) / 100,
//            5 => ($userLevelSend->where('level', 5)->value('team_ratio')) / 100,
//        ];
        $t = [
            1 => 0,
            2 => 0,
            3 => 0,
            4 => 0,
            5 => 0,
        ];

        foreach ($parentArr as $k => $v) {
            $userInfo = $userModel->where('id', $v)->find();
            $userLeveInfo = $userLevelSend->where('level', $userInfo['level'])->find();
            if ($k <= 3) {
//                $f = [
//                    1 => $userLeveInfo['share1'] / 100,
//                    2 => $userLeveInfo['share2'] / 100,
//                    3 => $userLeveInfo['share3'] / 100,
//                ];
                if ($f[$k] > 0) {

                    $addNum = bcmul($num, $f[$k], 5);
                    $mywalletLogModel->addLog($v, $addNum, 'fxtc', '消费' . $k . '粉奖励', 2, 1);
                    $mywalletModel->where('user_id', $v)->setInc('fxtc', $addNum);
                    $mywalletModel->where('user_id', $v)->setInc('bonus_total', $addNum);
                }

            }
            if ($k == 1) {
                if ($userInfo['level'] < $myUserInfo['level']) {
                    continue;
                }
            } elseif ($k > 1) {
                $upUserInfo = $userModel->where('id', $parentArr[$k - 1])->find();
                if ($upUserInfo['level'] > $userInfo['level']) {
                    continue;
                }
            }

            if ($userInfo['level'] < 1) {
                continue;
            }
            if ($t[$userInfo['level']] == 0) {

                $sendRatio = $userLeveInfo['team_ratio'] / 100;
//                $sameRatio = $sendRatio / 100;
                $addNumTeam = bcmul($num, $sendRatio, 5);
                $mywalletLogModel->addLog($v, $addNumTeam, 'fzf', '团队' . $k . '粉奖励', 2, 1);
                $mywalletModel->where('user_id', $v)->setInc('fzf', $addNumTeam);
                //$mywalletModel->where('user_id', $v)->setInc('bonus_total', $addNumTeam);
                $t[$userInfo['level']]++;
            } elseif ($t[$userInfo['level']] == 1) {

                $sendRatio = $userLeveInfo['team_ratio'] / 100;

                $sameRatio = $userLeveInfo['same_ratio'] / 100;//同级奖励比例

                $addNumTeam = bcmul($num, $sendRatio, 5);//该级获得奖励

                $addNumTeam = bcmul($addNumTeam, $sameRatio, 5);//同级奖励

                $mywalletLogModel->addLog($v, $addNumTeam, 'fzf', '团队同级' . $k . '粉奖励', 2, 1);
                $mywalletModel->where('user_id', $v)->setInc('fzf', $addNumTeam);
                //$mywalletModel->where('user_id', $v)->setInc('bonus_total', $addNumTeam);
                $t[$userInfo['level']]++;
            } else {
                continue;
            }


        }


    }

    #用户升级
    public function userLevelUpd($uid)
    {
        $userModel = new User();
        $userInfo = $userModel->where('id', $uid)->find();
        if ($userInfo['level'] >= 5) {
            return true;
        }
        $mywalletInfo = self::where('user_id', $uid)->find();
        $countZhitui = $userModel->where('pid', $uid)->count('id');
        $total_num = $mywalletInfo['total_num'];
        $newLevel = $userInfo['level'] + 1;
        $userLevel = UserLevelSend::where('level', $newLevel)->find();
        if ($countZhitui >= $userLevel['zhitui'] && $total_num >= $userLevel['team_total_num']) {
            $userModel->where('id', $uid)->setInc('level');
        }
        return true;
    }


    #生成个人中心气泡
    public function getInsRatio($uid, $num, $remark)
    {
        if ($num > 0) {
            $setNum = 4;
            $oneNum = bcdiv($num, $setNum, 5);
            for ($i = 0; $i < $setNum; $i++) {
                Db('ratio_list')->insert([
                    'uid' => $uid,
                    'ratio' => $oneNum,
                    'remark' => $remark,
                    'create_time' => time()
                ]);
            }
        }
        return true;
    }


    static public function cnyToGyg($num){
        $getToday = Proportion::getToday();
        if($getToday <= 0 || $num <= 0) return 0;
        return bcdiv($num,$getToday,2);
    }
}